package org.abc.program.controller.admin;

import com.github.pagehelper.util.StringUtil;
import org.abc.program.entity.User;
import org.abc.program.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/system")
public class SystemController {

	@Resource
	private UserService userService;

	// 登录页面接口
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String goLogin() {
		return "login";
	}

	// 登录验证表单
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody  // 表单的传输要json注解
	public Map<String, String> doLogin(User user, String cpacha, HttpServletRequest request) {
		HashMap<String, String> map = new HashMap<String, String>();

		if (user == null) {
			map.put("type", "error");
			map.put("msg", "请填写用户信息");
			return map;
		}

		if (StringUtil.isEmpty(cpacha)) {
			map.put("type", "error");
			map.put("msg", "请输入验证码");
			return map;
		}
		if (StringUtil.isEmpty(user.getUsername())) {
			map.put("type", "error");
			map.put("msg", "请填写用户名");
			return map;
		}

		if (StringUtil.isEmpty(user.getPassword())) {
			map.put("type", "error");
			map.put("msg", "请填写密码");
			return map;
		}

		Object loginCpacha = request.getSession().getAttribute("loginCpacha");

		if (loginCpacha == null) {
			map.put("type", "error");
			map.put("msg", "会话超时，请刷新页面！");
			return map;
		}
		if (!cpacha.toUpperCase().equals(loginCpacha.toString().toUpperCase())) {
			map.put("type", "error");
			map.put("msg", "验证码错误！");
			return map;
		}

		// 向数据库查询数据项
		User userByName = userService.getUserByName(user.getUsername());

		if (userByName == null) {
			map.put("type", "error");
			map.put("msg", "该用户名不存在！");
			return map;
		}

		/**
		 * 传进来的密码是否匹配数据库的密码
		 */
		if (!user.getPassword().equals(userByName.getPassword())) {
			map.put("type", "error");
			map.put("msg", "密码错误！");
			return map;
		}

		// 用户名，密码，验证码成功
		request.getSession().setAttribute("user", userByName);
		map.put("type", "success");
		map.put("msg", "登录成功");
		return map;
	}

	/**
	 * 登录成功后页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String toIndex() {
		return "index";
	}

	@RequestMapping(value = "/welcome", method = RequestMethod.GET)
	public String welcome() {
		return "welcome";
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request) {
		request.getSession().setAttribute("user",null);
		return "redirect:login";
	}
}
